<template>
  <div class="index">
    <div class="wrapper" :class="isMobile ? 'mobile' : 'web'" v-if="resuleVisible">
      <div class="backedit" @click="backToEdit"><i class="iconfont icon-fanhui"></i>返回上一层</div>
      <div class="question-user-list">
        <div v-for="(item, index) in formResult" :key="index" class="user-item">
          <div style="cursor: pointer;" @click="updateForm(item)">
            <div class="user-name">{{ item.userName || '匿名' }}</div>
            <div class="user-time">提交于{{ item.createTime }}</div>
          </div>
          <a v-if="isDel" @click="delUserResult(item, index)">删除</a>
        </div>
      </div>

    </div>
    <template v-else>
      <ProgressBar />
      <div class="wrapper" ref="boxRef" :class="isMobile ? 'mobile' : 'web'">
        <HeaderContent :bannerConf="bannerConf" :readonly="true" />
        <div class="content">
          <SubTitle :metaData="metaData" :readonly="true"></SubTitle>
          <MainTitle :bannerConf="bannerConf" :readonly="true"></MainTitle>
          <MainRenderer ref="mainRef"></MainRenderer>
          <SubmitButton
            :validate="validate"
            :submitConf="submitConf"
            :readonly="true"
            :renderData="renderData"
            @submit="handleSubmit"
          ></SubmitButton>
          <LogoIcon :logo-conf="logoConf" :readonly="true" @click="login" />
        </div>
        <div class="footer">
          <div class="btntabs">
            <div class="btntabs-btn" @click="editForm" v-if="canModify && !isMobile">编辑活动</div>
            <!-- <div class="btntabs-btn" @click="publicForm">生成二维码</div> -->
            <div class="btntabs-btn" @click="newForm" v-if="formResult?.length&&isMultiple">再填一份</div>
            <div class="btntabs-btn" @click="modifyForm" v-if="formResult?.length&&isUpdate">修改结果</div>
          </div>
        </div>

        
        <div class="qrcode-wrapper-pc" @click="publicForm">
          <img :src="qRCodeImg" />
        </div>
      </div>
    </template>
  </div>
</template>
<script setup>
import { computed, ref, onMounted } from 'vue'
import { get as _get } from 'lodash-es'
// 20240805改了store
// import { useStore } from 'vuex'
import store from '@/render/store/index'
import { useRouter,useRoute } from 'vue-router'
// @ts-ignore
import communalLoader from '@materials/communals/communalLoader.js'
import MainRenderer from '../components/MainRenderer.vue'
import AlertDialog from '../components/AlertDialog.vue'
import QrcodeDialog from '../components/QrcodeDialog.vue'
import LoginDialog from '../components/LoginDialog.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
import ProgressBar from '../components/ProgressBar.vue'

import { noLoginBatchSave as submitForm, del as deleteById } from '@/management/api/dataform-result'
import { loadLocalPage } from '@/management/api/eco/appcenter'

import useCommandComponent from '../hooks/useCommandComponent'
import QRCode from 'qrcode'
import path from 'path'

const props = defineProps({
  questionInfo: {
    type: Object,
    default: () => ({})
  },
  isMobile: {
    type: Boolean,
    default: false
  }
})

const HeaderContent = communalLoader.loadComponent('HeaderContent')
const MainTitle = communalLoader.loadComponent('MainTitle')
const SubTitle = communalLoader.loadComponent('SubTitle')
const SubmitButton = communalLoader.loadComponent('SubmitButton')
const LogoIcon = communalLoader.loadComponent('LogoIcon')

const mainRef = ref(null)
const boxRef = ref(null)

const alert = useCommandComponent(AlertDialog)
const handleLogin = useCommandComponent(LoginDialog)
const confirm = useCommandComponent(ConfirmDialog)
const qrcode = useCommandComponent(QrcodeDialog)

// const store = useStore()
const router = useRouter()

const route = useRoute()

const bannerConf = computed(() => store.state?.bannerConf || {})
const metaData = computed(() => store.state?.metaData || {
  creatorId: '',
  isMultiple: '',
  isDel: '',
  isUpdate: ''
})
const renderData = computed(() => store.getters.renderData)
const submitConf = computed(() => store.state?.submitConf || {})
const logoConf = computed(() => store.state?.bottomConf || {})
const dataConf = computed(() => _get(store, 'state.dataConf.dataList', []))
const surveyPath = computed(() => store.state?.surveyPath || '')
const formResult = computed(() => {
  let list = store.state?.formResult || []
  return list.map((item) => {
    return {
      ...item
    }
  })
})

const canModify = computed(() => {
  return metaData.value?.creatorId === (window).$app?.user?.userId
})
const isMultiple = computed(() => {
  return metaData.value?.isMultiple === '1'
})
const isDel = computed(() => {
  return metaData.value?.isDel === '1'
})
const isUpdate = computed(() => {
  return metaData.value?.isUpdate === '1'
})
const resuleVisible = ref(false)
const oldBatchCode = ref('')

const routerMode = ref(import.meta.env.VITE_ROUTER_MODE)

const login = () => {
  // handleLogin({
  //   onClose: () => {
  //     let href = `${(location.origin+'/myactivity')}/forms/${surveyPath.value}/publish`
  //     loadLocalPage(href)
  //   }
  // })
}
const editForm = () => {
  let href = `${(location.origin+'/myactivity')}/forms/${surveyPath.value}/edit`
  if (routerMode.value === 'hash') {
    href = `${(location.origin+'/myactivity')}/#/forms/${surveyPath.value}/edit`
  }
  loadLocalPage(href)
}

const qRCodeImg = ref('')

// const routerMode = ref(import.meta.env.VITE_ROUTER_MODE);
const convertUrlToQRCode = async () => {
  try {
    let fullUrl = `${(window).$app?.homePage||(location.origin+'/myactivity')}/render/${surveyPath.value}?t=${Date.now()}`
    if (routerMode.value === 'hash') {
      fullUrl = `${(window).$app?.homePage||(location.origin+'/myactivity')}/render.html#/${surveyPath.value}?t=${Date.now()}`
    }
    const res = await QRCode.toDataURL(fullUrl)
    qRCodeImg.value = res
  } catch (err) {
    console.log(err)
  }
}
const publicForm = () => {
  let fullUrl = ''

  if (metaData.value) {
    fullUrl = `${(window).$app?.homePage||(location.origin+'/myactivity')}/render/${surveyPath.value}?t=${Date.now()}`
    if (routerMode.value === 'hash') {
      fullUrl = `${(window).$app?.homePage||(location.origin+'/myactivity')}/render.html#/${surveyPath.value}?t=${Date.now()}`
    }
  }

  qrcode({
    url: fullUrl || ''
  })
}
const newForm = () => {
  oldBatchCode.value = ''
  loadLocalPage()
}
const delUserResult = async (item, index) => {
  (window).$ui.msgBox({
    title: '提示',
    type: 'warning',
    message: '是否确认删除？',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    showClose: false
  }).then(async() => {
    const res = await deleteById({
      id: item.batchCode,
      formId: surveyPath.value,
      userId: item.userId
    })
    oldBatchCode.value = ''
    if (res?.serverResult?.resultCode !== '200') {
      (window).$ui.msg(res?.serverResult?.resultMessage)
      return
    } else {
      formResult.value.splice(index, 1)
      console.log('formResult.value', formResult.value)
      store.commit('setFormResult', formResult.value)
    }
  })
}
const updateForm = (item) => {
  console.log('item', item)
  console.log('dataConf.value', dataConf.value)
  let myResultList = item.myDataFormResultList
  dataConf.value.forEach((item) => {
    item.value = item.value || ''
    let idx = myResultList.findIndex((itm) => itm.attrId === item.attrId)
    if (idx > -1) {
      const data = {
        key: item.attrId,
        value: myResultList[idx].dataFormResult
      }
      store.commit('changeFormData', data)
    }
  })
  oldBatchCode.value = item.batchCode
  resuleVisible.value = false
}
const backToEdit = () => {
  resuleVisible.value = false
  oldBatchCode.value = ''
}
const modifyForm = () => {
  resuleVisible.value = true
  oldBatchCode.value = ''
}
const validate = (cbk) => {
  const index = 0
  mainRef.value.$refs.formGroup[index].validate(cbk)
}

const normalizationRequestBody = () => {
  const enterTime = store.state.enterTime || 0
  let insertList = []
  const formValues = store.state.formValues
  Object.keys(formValues).forEach((item) => {
    let fvalue = formValues[item]
    let param = {
      formId: surveyPath.value,
      attrId: item,
      dataFormResult: ''
    }
    if (Array.isArray(fvalue) && fvalue.length > 0 && typeof fvalue[0] === 'object' && fvalue[0] !== null) {
      // 上传的文件
      param.dataFormResult = fvalue.map((item) => item.filename).join('#')
    } else if (Array.isArray(fvalue)) {
      param.dataFormResult = fvalue.join('#')
      param.multiSelect = '1'
    } else {
      param.dataFormResult = fvalue
    }
    
    insertList.push(param)
  })
  console.log(insertList)

  const result = {
    oldBatchCode: oldBatchCode.value,
    formId: surveyPath.value,
    insertList: insertList,
    difTime: Date.now() - enterTime,
    clientTime: Date.now()
  }

  return result
}

const submitSurver = async () => {
  try {
    const params = normalizationRequestBody()
    console.log(route)
    console.log(params)
    const res = await submitForm(params)
    if (res?.serverResult?.resultCode === '200') {
      if (route.path == '/') {
        router.push({name: 'previewIndexSuccessPage'})
      } else {
        router.push({ name: 'previewSuccessPage' })
      }
      
    } else {
      alert({
        title: res?.serverResult?.resultMessage || '提交失败'
      })
    }
  } catch (error) {
    console.log(error)
  }
}

const handleSubmit = () => {
  const confirmAgain = store.state?.submitConf?.confirmAgain || {}
  const { again_text, is_again } = confirmAgain

  if (is_again) {
    confirm({
      title: again_text,
      onConfirm: async () => {
        try {
          submitSurver()
        } catch (error) {
          console.log(error)
        } finally {
          confirm.close()
        }
      }
    })
  } else {
    submitSurver()
  }
}

onMounted(() => {
  convertUrlToQRCode()
  console.log('renderData.value', renderData.value)
  if (localStorage.getItem('submitSuccess')) {
    localStorage.removeItem('submitSuccess')
    newForm()
  }
})

</script>
<style scoped lang="scss">
@use '@/materials/questions/common/css/icon.scss' as *;

.index {
  min-height: 100%;

  .wrapper {
    min-height: 100%;
    background-color: var(--primary-background-color);
    display: flex;
    flex-direction: column;

    .content {
      flex: 1;
      margin: 0 0.3rem;
      background: var(--primary-background-color);
      border-radius: 8px 8px 0 0;
      height: 100%;
    }

    .footer {
      width: 100%;
      padding: 0 0.3rem;
      background-color: #f1f2f3;
      border-top: 2px solid #f1f2f3;
    }
    .btntabs {
      display: flex;
      border-radius: 8px;
      justify-content: space-between;
      background: #FFFFFF;
      box-shadow: 0px 6px 16px 1px rgba(0,0,0,0.08);
    }
    .btntabs-btn {
      flex: 1;
      width: 50%;
      text-align: center;
      padding: 10px;
      cursor: pointer;
      &:hover {
        color: var(--primary-color);
      }
    }

    .backedit {
      cursor: pointer;
      padding: 10px;
    }
    .question-user-list {
      padding: 10px 20px;
      .user-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        border-bottom: 1px solid #e6e6e6;
        a {
          font-size: 12px;
          &:hover {
            color: $primary-color;
          }
        }
      }
      .user-name {
        font-size: 16px;
      }
      .user-time {
        color: #999;
      }
    }

    .qrcode-wrapper-pc {
      display: none;
    }
  }
}
@media (min-width: 930px) {
  .qrcode-wrapper-pc {
    position: fixed;
    display: flex !important;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    background: #ffffff;
    text-align: center;
    border-radius: 4px;
    padding: 5px;
    font-size: 12px;
    width: 60px;
    height: 60px;
    right: 0;
    bottom: 30%;
    img {
      width: 50px;
      height: 50px;
    }
  }
  .qrcode-wrapper-pc:hover {
    width: 200px;
    height: 200px;
    img {
      width: 190px;
      height: 190px;
    }
  }
}
</style>
